package org.zjvis.datascience.service.dag;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

/**
 * @description 任务结果绑定对象
 * @date 2021-12-24
 */
@Data
public class TaskRunnerResult {

    private int status;

    private String output;

    private static final String RESULT = "result";

    private static final String OUTPUT_PARAM = "output_params";

    public TaskRunnerResult() {

    }

    public TaskRunnerResult(int status, String output) {
        this.status = status;
        this.output = output;
    }

    public static TaskRunnerResult fail() {
        String errorTpl = "{\"status\":500, \"error_msg\":\"%s\"}";
        return new TaskRunnerResult(-1, String.format(errorTpl, "job execution failed abnormally."));
    }

    public static TaskRunnerResult fail(String msg) {
        String errorTpl = "{\"status\":500, \"error_msg\":\"%s\"}";
        return new TaskRunnerResult(-1, String.format(errorTpl, msg));
    }

    public static TaskRunnerResult ok() {
        return new TaskRunnerResult(0, "");
    }

    public static TaskRunnerResult ok(String msg) {
        return new TaskRunnerResult(0, msg);
    }

    public JSONArray getOutParams() {
        JSONObject jsonObject = JSONObject.parseObject(this.getOutput());
        if (jsonObject.containsKey(RESULT)) {
            jsonObject = jsonObject.getJSONObject(RESULT);
            return jsonObject.containsKey(OUTPUT_PARAM) ? jsonObject.getJSONArray(OUTPUT_PARAM) : new JSONArray();
        }
        return new JSONArray();

    }

}
